package com.michaelbulava.TFS.vcs.utils;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vcs.VcsException;
import com.michaelbulava.TFS.log.FileLogger;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Failure;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.SeverityType;
import com.microsoft.tfs.util.Check;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * Created by MichaelA on 8/6/2015.
 */
public class TFSUtil {
    private static final Logger log = FileLogger.getInstance(TFSUtil.class);

    public static List<VcsException> getVcsExceptions(Collection<Failure> failures)
    {
        List<VcsException> exceptions = new ArrayList();
        for (Failure failure : failures) {
            if (failure.getSeverity() != SeverityType.WARNING) {
                exceptions.add(new VcsException(failure.getMessage()));
            }
        }
        return exceptions;
    }

    public static List<VcsException> getVcsExceptions(Failure[] failures){
        return getVcsExceptions(Arrays.asList(failures));
    }

    public static VcsException collectionException(Collection<VcsException> exceptions){
        Check.isTrue(!exceptions.isEmpty(), "No exceptions to collect");
        if (exceptions.size() == 1)
            return exceptions.iterator().next();
        log.debug(String.format("combining %d exceptions into 1", exceptions.size()));

        StringBuilder sb = new StringBuilder();
        for(VcsException e : exceptions){
            if (sb.length() > 0)
                sb.append("\n");
            sb.append(e.getMessage());
        }
        log.debug("Generated error message: " + sb.toString());
        return new VcsException(sb.toString());
    }
}
